import { notification } from 'antd';
import { sm4, sm2, sm3 } from 'sm-crypto';
// import { testMock, sdsdsdsd } from './mock';
const firstOnlyiv = 'f44c49544e68478d'; /** IV前段 */

const pubkey =
  '039e4e357cf4fd771334f7bca8e152305b83a864c8862302283fd1a39519fdd8a2'; // 加
/** 私 */
const firstPivKey = '8aba3f76ae387d58769de2a3c7af7d947';
const secPivKey = '04c2ed5bc900b8f9ab890fc310f29e0';

const { CUSTOM_ENV } = process.env;

const secOnlyiv = 'd861bd3521f9e6ce'; /** IV后段 */

export let getUrl = window.location.hash.includes('/enterprises');
// 消息提示
export function NewsTips(description, params) {
  if (params) {
    const {
      type = 'warning',
      placement = 'topRight',
      message = '消息提示',
    } = params;
    notification[type]({
      message,
      description,
      placement,
    });
  } else {
    notification.warning({
      message: '消息提示',
      description,
      placement: 'topRight',
    });
  }
}
export function apiAuth() {
  let api;
  if (!CUSTOM_ENV) {
    api = '/api/';
  } else if (
    CUSTOM_ENV === 'safe' ||
    CUSTOM_ENV === 'nsafe' ||
    CUSTOM_ENV === 'devsafe'
  ) {
    api = '/api/base/glzz/';
  } else {
    api = '/api/base/';
  }
  return api;
}
function SM2EncryptVal(params) {
  return '04' + sm2.doEncrypt(params.toString(), pubkey, 1);
}

// get请求参数拼接
export function transformParams(params = {}) {
  const parts = [];
  Object.keys(params).forEach((key) => {
    const val = params[key];
    if (val !== null && typeof val !== 'undefined') {
      let temp = null;
      if (CUSTOM_ENV == 'nsafe' || CUSTOM_ENV == 'npre' || !CUSTOM_ENV) {
        temp = `${key}=${val}`;
      } else {
        temp = `${key}=${SM2EncryptVal(val)}`;
        // temp = `${key}=${val}`;
      }
      parts.push(temp);
    }
  });
  return parts.join('&');
}

// post请求参数处理
export function transformObject(params = {}) {
  const newObj = {};
  Object.keys(params).forEach((key) => {
    const val = params[key];
    if (val !== null && typeof val !== 'undefined') {
      newObj[key] = val;
    }
  });
  return newObj;
}

export function fontSize(res) {
  const clientWidth =
    window.innerWidth ||
    document.documentElement.clientWidth ||
    document.body.clientWidth;
  if (!clientWidth) return;
  let fontSize = clientWidth / 1920;
  return res * fontSize;
}

const htmlIllegalRegex = /(\b(a|iframe|body|form|base|img|src|style|div|object|meta|link|input|comment|br|&nbsp;|&quot;|&amp;|&#x27;|&#x2F;|&lt;|&gt;|&AElig;|&Aacute;|&Acirc;|&Agrave;|&Aring;|&Atilde;|&Auml;|&Ccedil;|&ETH;|&Eacute;|&Ecirc;|&Egrave;|&Euml;|&Iacute;|&Icirc;|&Igrave;|&Iuml;|&Ntilde;|&Oacute;|&Ocirc;|&Ograve;|&Oslash;|&Otilde;|&Ouml;|&THORN;|&Uacute;|&Ucirc;|&Ugrave;|&Uuml;|&Yacute;|&aacute;|&acirc;|&aelig;|&agrave;|&aring;|&atilde;|&auml;|&ccedil;|&eacute;|&ecirc;|&egrave;|&eth;|&euml;|&iacute;|&icirc;|&igrave;|&iuml;|&ntilde;|&oacute;|&ocirc;|&ograve;|&oslash;|&otilde;|&ouml;|&szlig;|&thorn;|&uacute;|&ucirc;|&ugrave;|&uuml;|&yacute;|&yuml;|&cent;|\"|&|&#39)\b)/i; // js 防注入
const sqlIllegalRegex = /(\b(and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators|%|netlocalgroup administrators|net user|like'|table|from|grant|use|column_name|group_concat|information_schema.columns|table_schema|union|where|order|by|join|modify|\+|-|--|into|substr|ascii|'|%27|\(|%28|\)|%29|%25|having|1=1|\\\*)\b)/i;
const urlIllegalRegex = /(\b(%2B|%20|%2F|%3F|%25|%23|%26|%30|%27|%26|%22|%28|%29|%2a|%2b|%2d)\b)/i;
const jsIllegalRegex = /\/\\\*|%|<|>|&|"|’|'|'|"|\/|\\|\\r|\\n|\\f|\\t|\\b|\\\\|!|@|#|\$|\^|\*|\(|\)|~|\?|:|;|`|-|=|\[|\]|javascript|script|function|jscript|vbscript|onfocus|onblur|alert|location|document|window|onclick|href|<!--|--|->|onfocus|confirm|prompt|data:|\\u003e|\\u003c|eval|url|expr|URLUnencoded|referrer|write|writeln|body.innerHtml|execScript|setInterval|setTimeout|open|navigate|srcdoc|%0a|onerror|<\/|\.|\(\)|\/\/|\/\*|\\\*\//i;
const reg = new RegExp(
  "[`~!@#$^&*()=|{}':;',\\.<>/?~！@%#￥……&*（）——|{}【】‘；：”“'。，、？\\n\\s\\r\\t\\b\\f·]|[\\\\/]|[_+《》-]|[///*</]|[\\*/]|[\\*/]",
);

/** 是否存在特殊字符 以及html关键词过滤*/
export function IsSpecialCharacters(content) {
  if (content) {
    const value = content.toLowerCase();
    if (
      htmlIllegalRegex.test(value) ||
      sqlIllegalRegex.test(value) ||
      urlIllegalRegex.test(value) ||
      jsIllegalRegex.test(value) ||
      reg.test(value)
    ) {
      return true;
    }
    return false;
  }
}

/** 过滤接口返回数据 */
export function IsSpecialData(content) {
  if (content) {
    const value = content.toLowerCase();
    if (
      htmlIllegalRegex.test(value) ||
      sqlIllegalRegex.test(value) ||
      urlIllegalRegex.test(value) ||
      jsIllegalRegex.test(value) ||
      reg.test(value)
    ) {
      return false;
    }
    return true;
  }
}

/** 接口防重 */
export function AntiGravity() {
  return null;
}

/**
 *
 * @param {*} 返回data数据
 * @secretKey 解密key
 * @secretSm sm3比对数据完整性
 * @secretFields 需要解密字段
 * @description: 获取对象解密
 */

export function getObjDecryptData(params, url) {
  let result = params;
  if (params) {
    const { secrK, data } = params;
    if (secrK) {
      const sm4Key = getSM2Key(secrK);
      let desc = null;
      try {
        desc = sm4
          .decrypt(data, sm4Key, { mode: 'cbc', iv: firstOnlyiv + secOnlyiv })
          .replace(/\u0000/g, '');
        const SM3Value = desc.split('+');
        // const SM3Compare = hashcode(sm3(SM3Value[1])) + '';
        const SM3Compare = sm3(SM3Value[1]);
        if (SM3Compare === SM3Value[0]) {
          result['data'] = JSON.parse(SM3Value[1]);
        } else {
          notification.error({
            message: '消息提示',
            description: '数据完整性被破坏',
            placement: 'topRight',
          });
        }
      } catch (error) {
        notification.error({
          message: '消息提示',
          description: '数据完整性被破坏',
          placement: 'topRight',
        });
      }
    }
  }
  return result;
}

function getSM2Key(secretKey) {
  const kys = secretKey.slice(2);
  const sm2Key = sm2.doDecrypt(kys, firstPivKey + secPivKey, 1);
  return sm2Key;
}

/** 获取ISC回跳ticket */
export function getQueryValue(queryName) {
  const url = window.location.href;
  let p = url.split('?')[1];
  let params = new URLSearchParams(p);
  return params.get(queryName);
}

/** 现场开发环境地址  */
const ISCUrl = window.getIscUrl;

/** 根据不同环境获取对应地址 */
export function getEnvURL() {
  const { origin } = window.location;
  let url = null;
  if (CUSTOM_ENV && CUSTOM_ENV !== 'devsafe') {
    url = ISCUrl + origin;
  }
  return url;
}

export function formatRoundNum(num) {
  let integer = Math.ceil(num);
  let length = String(integer).length;
  return (
    Math.ceil(integer / Math.pow(10, length - 1)) * Math.pow(10, length - 1)
  );
}
export const Cookie = {
  set: function (key, value, extime, path) {
    //校验Key, key中不能有等号【=】
    if (key.indexOf('=') !== -1) {
      throw new Error('Cookie不支持key中使用等号【=】, key:' + key);
    }
    let exdate = new Date(); // 获取时间
    exdate.setTime(exdate.getTime() + extime * 1000); // 保存的天数
    // 字符串拼接cookie
    // eslint-disable-next-line camelcase
    window.document.cookie =
      key + '=' + value + ';path=' + path + ';expires=' + exdate.toGMTString();
  },

  remove: function (key) {
    Cookie.set(key, null, -1);
  },
};

/** 格式化数据 */
export const initFormat = (data, len = 2) => {
  if (!isNaN(Number(data))) {
    // 如果是数字
    if (Number.isInteger(Number(data))) {
      return Number(data);
    } else {
      return Number(Number(data).toFixed(len));
    }
  } else {
    return 0;
  }
};

/** 数据转换 */
export const dataConversion = (value, unit) => {
  if (!isNaN(Number(value))) {
    if (unit.includes('万') && Number(value) < 10000) {
      return { value: initFormat(value), unit };
    }
    if (unit.includes('万') && Number(value) >= 10000) {
      return {
        value: initFormat(Number(value) / 10000),
        unit: unit.replace('万', '亿'),
      };
    }
  } else {
    return { value: 0, unit };
  }
};
